package b1.mobile.blackberry.ui.component;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.FontFamily;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.container.HorizontalFieldManager;

public class SingleLineEditField extends Manager {

	static int background = 0x00FFFFFF;
	static int borderColor = 0x00808080;
	
	EditField _edit = new EditField(Field.USE_ALL_WIDTH){
		protected void paint(Graphics graphics) {
			getManager().invalidate();
			super.paint(graphics);
		};
	};
	Font _editFont = Font.getDefault();
	
	HorizontalFieldManager _hfm = new HorizontalFieldManager(Manager.HORIZONTAL_SCROLL);
	
	int _width;
	int _height;
	private String _text = "";
	
	public SingleLineEditField(long style){
		super(style | Manager.NO_HORIZONTAL_SCROLL);
		
		try {
			FontFamily ff = FontFamily.forName("Alpha Sans");
			_editFont = ff.getFont(Font.PLAIN, 6, Ui.UNITS_pt);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		_edit.setFont(_editFont);
		_hfm.add(_edit);
		_hfm.setPadding(8, 8, 8, 8);
		add(_hfm);
	}
	// TODO Auto-generated constructor stub}

	protected void sublayout(int width, int height) {
		layoutChild(_hfm, width, this.getPreferredHeight());
		setExtent(width, this.getPreferredHeight());
	}
	
	public int getPreferredHeight() {
		return 35;
	}
	
	protected void paint(Graphics graphics) {
		int previousColor = graphics.getColor();
		
		graphics.setColor(background);
		graphics.fillRoundRect(0, 0, getExtent().width, getExtent().height, 16, 16);
		
		graphics.setColor(borderColor);
		graphics.setStrokeWidth(2);
		graphics.drawRoundRect(0, 0, getExtent().width, getExtent().height, 16, 16);
		
		graphics.setColor(previousColor);

		getManager().invalidate();
		super.paint(graphics);
	}

	protected int nextFocus(int direction, boolean alt) {
		int index = this.getFieldWithFocusIndex();
		if(alt) {
			if(direction > 0) {
				// Action to perform if trackwheel is rolled up.
			}
			else {
				// Action to perform if trackwheel is rolled down.
			}
		}
		
		if (index == this.getFieldWithFocusIndex())
			return super.nextFocus(direction, alt);
		else
			return index;
	}

	public void setText(final String text) {
		if(UiApplication.isEventDispatchThread()){
			_edit.setText(text);
		} else {
			UiApplication.getApplication().invokeLater(new Runnable(){
				public void run() {
					_edit.setText(text);
				}
				
			});
		}
	}
	
	public String getText(){
		return _edit.getText();
	}
}
